<!--  这一段是直接用了uview的官方例子，然后自己改改 -->
<template>
	<view class="u-wrap">
<!-- 		<view class="u-search-box">
			<view class="u-search-inner">
				<u-icon name="search" color="#909399" :size="28"></u-icon>
				<text class="u-search-text">搜索</text>
			</view>
		</view> -->
		<view class="u-menu-wrap">
            <!-- 左边菜单 可滚动视图区域 -->
			<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop"
			 :scroll-into-view="itemId">
             <!-- tap.stop阻止冒泡 -->
				<view v-for="(item,index) in tabbar" :key="index" class='u-tab-item' :class="[current == index ? 'u-tab-item-active' : '']"
				 @tap.stop="swichMenu(index)">
                 <text class="u-line-1">{{item.menu_name}}</text>
                 <view v-if='complete_menu[item.menu_id]' class="menu-list-cell-num"><text style="color: #ffffff; margin:30%;">{{complete_menu[item.menu_id]}}</text></view>
				</view>
			</scroll-view>
            <!-- 右边菜单 可滚动视图区域 -->
			<scroll-view :scroll-top="scrollRightTop" scroll-y scroll-with-animation class="right-box" @scroll="rightScroll">
				<view class="page-view">
					<view class="class-item" :id="'item' + index" v-for="(item , index) in tabbar" :key="index">
						<view class="item-title">
							<text>{{item.menu_name}}</text>
						</view>
						<view>
							<view class='menuDetailDiv' v-for="(item1, index1) in item.lists" :key="index1">
								<!-- <image class="item-menu-image" :src="item1.icon" mode=""></image>
								<view class="item-menu-name">{{item1.title}}</view> -->
                                <view class='menuDetailDivImg'>
                                    <image class='menu-img' :src='item1.icon'></image>
                                </view>
                                <view class='menuDetailDivContent'>
                                    <text style="font-size:30upx;font-weight: bold;">{{item1.title}}</text>
                                    <text class='menuDetailDivContentDetails'>{{item1.details}}</text>
                                    <text class='menuDetailDivContentDetails'>月售 {{item1.monthSale}}</text>
                                    <view class='menuDetailDivContentDetailsPrice'>
                                        <view class='menuDetailDivContentDetailsPriceDiv'>
                                            <text class='presentPrice'>{{item1.presentPrice}}</text>
                                            <text class='menuDetailDivContentDetailsoriginalPrice shanchu'>{{item1.originalPrice}}</text>
                                        </view>
                                        <view class="addNum">
                                            <view v-if="complete_datas.find(element => element.id===item1.id)['num']>0" class='minusSign' @click="reduceGoods(item.menu_id, item1)"><text style="margin: 30%;">-</text></view>
                                            <view  v-if="complete_datas.find(element => element.id===item1.id)['num']>0" style="margin:0px 2rpx;"><text>{{complete_datas.find(element => element.id===item1.id)['num']}}</text></view>
                                            <view class='plush' @click="addGoods(item.menu_id, item1)"><text style="margin: 30%;">+</text></view>
                                        </view>
                                    </view>
                                </view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
       <view :class="[!modalShow?'db_div':'db_div_show']">
           <view class='footDivFlex' v-if='totalNum<=0'>
                <view class='footDivFlexMenu'>
                    <text style="font-size: 35upx;font-weight: bold;" class='footDivFlexMenusp'>未选购商品</text>
                    <text style="font-size: 27upx;">另需配送费 {{datas.distributionFee}}</text>
                </view>
                <view class='footDivFlexMenuqss'>
                    <text style="font-size: 27upx;">{{datas.standard}}起送</text>
                </view>
            </view>
            <view class='footDivFlex' v-else>
                <view>
                    <view class="footDivFlexTotalNum"><text style="color: #ffffff;">{{totalNum}}</text></view>
                </view>
                <!-- 不要使用@click="show=true"这种形式，在微信小程序中会失效，会报一个_vm.e0 is not a function错误 （这个错误我百度半天没找到答案，然后只能不停的注释代码，不停的试才找出问题）-->
                <view class='footDivFlexMenu' @click="setpopup">
                    <text style="font-size: 35upx;font-weight: bold;" class='footDivFlexMenusp'>¥{{totalPrice}}</text>
                    <text style="font-size: 27upx;">另需配送费 {{datas.distributionFee}}</text>
                </view>
                <view class='footDivFlexMenuqss' @click="settlement" >
                    <text style="font-size: 27upx;">去结算</text>
                </view>
            </view>
       </view>
       <!-- 弹出层 -->
       <u-popup mode="bottom" v-model="xshow" style="margin-bottom:80px ;">
            <view class="content">
                <view style="background-color:#ffffff; display: flex; flex-direction: row-reverse;" @click="emptyData"><text style="margin: 10px; font-size: 30upx;">清空购物车</text></view>
                <scroll-view scroll-y="true" style="height: 400rpx;margin-bottom:80px;">
                    <view>
                        <view v-for="data of complete_datas" :key="data.id">
                            <view v-if='data.num>0' class='wxcPopupListCell'>
                                    <view>
                                        <image :src='data.icon' style="width: 70px;height: 70px;" ></image>
                                    </view>
                                    <view>
                                        <text>{{data.title}}</text>
                                    </view>
                                    <view class="addNum">
                                        <view v-if="complete_datas.find(element => element.id===data.id)['num']" class='minusSign' @click="reduceGoods(data.menu_id, data)"><text style="margin: 30%;">-</text></view>
                                        <view v-if="complete_datas.find(element => element.id===data.id)['num']" style="margin:0px 10px;"><text>{{complete_datas.find(element => element.id===data.id)['num']}}</text></view>
                                        <view class='plush' @click="addGoods(data.menu_id, data)"><text style="margin: 30%;">+</text></view>
                                    </view>
                                </view>
                        </view>
                    </view>
                </scroll-view>
            </view>
        </u-popup>
        <u-modal v-model="modalShow" :mask-close-able="true" title='结算'>
            <view style="margin: 20px 30%;">
                <view>商品价格：{{totalPrice}}</view>
                <view>配送费：{{datas.distributionFee}}</view>
            </view>
        </u-modal>
	</view>
</template>
<script>
	import classifyData from '../../static/classify.data.js';
    import Config from "../../static/business_config.js";
	export default {
		data() {
			return {
                modalShow: false,
                xshow: false,
				scrollTop: 0, //tab标题的滚动条位置
				oldScrollTop: 0,
				current: 0, // 预设当前项的值
				menuHeight: 0, // 左边菜单的高度
				menuItemHeight: 0, // 左边菜单item的高度
				itemId: '', // 栏目右边scroll-view用于滚动的id
				tabbar: Config.menuDetails, // 数据
                // tabbar: classifyData,
				// menuItemPos: [],
				arr: [], // 分类的每个高度列表
				scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
				timer: null, // 定时器
                complete_datas: [], // 分类左列表对应添加数量
                complete_menu: {}, // 菜单右列表对应的添加数量
                totalNum: 0, // 添加的总数量
                totalPrice: 0, // 添加的总价格
			}
		},
        // 父组件传过来的URL参数数据
        props:["datas"],
		onLoad() {
		},
        onShow(){
        },
		onReady() {
            // 初次渲染以后触发，所以修改了高度相关的css，js等，需要重新刷新一下，不然会发现左右联动会出问题
            // 需要操作dom的操作都需要放在这里，等待渲染完以后才能用
			this.getMenuItemTop();
            this.initdef();
		},
        // H5端没有 onReady，onLoad这些生命周期，还是用vue的 
        // #ifdef H5
        mounted(){
            this.getMenuItemTop();
            this.initdef();
        },
        // #endif
        // 
		methods: {
            initdef(){
                // 需要初始化数据，不然无法使用
                // const self = this;
                let new_complete_menu = {};
                let new_complete_datas = [];
                for(let k of Config.menuDetails){
                    new_complete_menu[k.menu_id] = 0;
                    for(let kk of k.lists){
                        kk['menu_id'] = k.menu_id;
                        new_complete_datas.push(kk);
                    }
                };
                // 需要初始化数据，不然无法使用
                this.complete_menu = new_complete_menu;
                this.complete_datas = new_complete_datas;
            },
			// 点击左边的栏目切换
			async swichMenu(index) {
				if(this.arr.length == 0) {
					await this.getMenuItemTop();
				}
				if (index == this.current) return;
				this.scrollRightTop = this.oldScrollTop;
				this.$nextTick(function(){
					this.scrollRightTop = this.arr[index];
					this.current = index;
					this.leftMenuStatus(index);
				})
			},
			// 获取一个目标元素的高度
			getElRect(elClass, dataVal) {
				new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.' + elClass).fields({
						size: true
					}, res => {
						// 如果节点尚未生成，res值为null，循环调用执行
						if (!res) {
							setTimeout(() => {
								this.getElRect(elClass);
							}, 10);
							return;
						}
						this[dataVal] = res.height;
						resolve();
					}).exec();
				})
			},
			// 观测元素相交状态
			async observer() {
				this.tabbar.map((val, index) => {
					let observer = uni.createIntersectionObserver(this);
					// 检测右边scroll-view的id为itemxx的元素与right-box的相交状态
					// 如果跟.right-box底部相交，就动态设置左边栏目的活动状态
					observer.relativeTo('.right-box', {
						top: 0
					}).observe('#item' + index, res => {
						if (res.intersectionRatio > 0) {
							let id = res.id.substring(4);
							this.leftMenuStatus(id);
						}
					})
				})
			},
			// 设置左边菜单的滚动状态
			async leftMenuStatus(index) {
				this.current = index;
				// 如果为0，意味着尚未初始化
				if (this.menuHeight == 0 || this.menuItemHeight == 0) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
					await this.getElRect('u-tab-item', 'menuItemHeight');
				}
				// 将菜单活动item垂直居中
				this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
			},
			// 获取右边菜单每个item到顶部的距离
			getMenuItemTop() {
				new Promise(resolve => {
                    // let selectorQuery = uni.createSelectorQuery() 这个是源码，但是因为这是一个组件所以需要加上.in()，不然的话H5有效，微信小程序无效
					let selectorQuery = uni.createSelectorQuery().in(this);
					selectorQuery.selectAll('.class-item').boundingClientRect((rects) => {
						// 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
						if(!rects.length) {
							setTimeout(() => {
								this.getMenuItemTop();
							}, 10);
							return;
						}
						rects.forEach((rect) => {
							// 这里减去rects[0].top，是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
                            // 将所有类别的高度列表
							this.arr.push(rect.top - rects[0].top);
							resolve();
						})
					}).exec()
				})
			},
			// 右边菜单滚动
            /* 这里有个问题，点击左边菜单，右边的相同类别高度会上移顶端，
            但是，因为这里一个奇怪的设定为了对应最后面的类别，左边选中菜单会和你选中的不一致，
            比如你选中了A类别，但是因为A内容很少，右边出了A还有B和C的内容，这里的设定是显示最后的类别，这样的话，左边菜单你明明选中了A，但是会自动移到C，
             我觉得这样很奇怪，就修改了，左右高度一致就显示*/
			async rightScroll(e) {
				this.oldScrollTop = e.detail.scrollTop;
				if(this.arr.length == 0) {
					await this.getMenuItemTop();
				}
				if(this.timer) return ;
				if(!this.menuHeight) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
				}
				setTimeout(() => { // 节流
					this.timer = null;
					// scrollHeight为右边菜单垂直中点位置
                    // 原来他会加上菜单高度的一半，我去掉了，这样问题就解决了
					// let scrollHeight = e.detail.scrollTop + this.menuHeight / 2;
                    let scrollHeight = e.detail.scrollTop;
					for (let i = 0; i < this.arr.length; i++) {
						let height1 = this.arr[i];
						let height2 = this.arr[i + 1] || 0;
						// 如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
						if (!height2 || scrollHeight >= height1 && scrollHeight < height2) {
							this.leftMenuStatus(i);
							return ;
						}
					}
				}, 10)
			},
            // 添加数量
            addGoods(menu_id, data){
              // 本来就想简单写一下，所以数据结构有点问题，这里处理一下
              let new_price = Number(data.presentPrice.replace('¥', ''));
              // 菜品数量增加和菜品种类的增加
              const self = this;
              // 这里的数据购物车需要
              let find_data = self.complete_datas.find(element => element.id===data.id)
              if(find_data['num']<=0 || find_data['num']==null){
                  find_data['num']= 0 + 1;
                  self.totalPrice = self.totalPrice + new_price;
                  self.totalNum = self.totalNum + 1;
              }else{
                  find_data['num']= find_data['num'] + 1;
                  find_data['price']= find_data['price'] + new_price;
                  self.totalPrice = self.totalPrice + new_price;
                  self.totalNum = self.totalNum + 1;
              }
              if(self.complete_menu[menu_id] <= 0 || self.complete_menu[menu_id] == null){
                  self.complete_menu[menu_id] = 0 + 1;
              }else{
                  self.complete_menu[menu_id] = self.complete_menu[menu_id] + 1;
              }
          },
          // 减少数量
          reduceGoods(menu_id, data){
              // 本来就想简单写一下，所以数据结构有点问题，这里处理一下
              let new_price = Number(data.presentPrice.replace('¥', ''));
              // 菜品数量减少和菜品种类的减少
              const self = this;
              // 这里的数据购物车需要
              let find_data = self.complete_datas.find(element => element.id===data.id)
              if(find_data['num']<=0 || find_data['num']==null){
                  find_data['num']= 0;
                  self.totalPrice = 0;
                  find_data['price']= 0;
                  self.totalNum = 0;
              }else{
                  find_data['num']= find_data['num'] - 1;
                  find_data['price']= find_data['price'] - new_price;
                  self.totalPrice = self.totalPrice - new_price; 
                  self.totalNum = self.totalNum - 1;
              }
              if(self.complete_menu[menu_id] <= 0 || self.complete_menu[menu_id] == null){
                  self.complete_menu[menu_id] = 0;
              }else{
                  self.complete_menu[menu_id] = self.complete_menu[menu_id] - 1;
              }
              // 数量为0，弹出层消失
              if(self.totalNum==0){
                  self.show = false;
              }
          },
        // 清空购物车
        emptyData(){
          const self = this;
          let new_complete_menu = {};
          let new_complete_datas = [];
          for(let k of Config.menuDetails){
              new_complete_menu[k.menu_id] = 0;
              for(let kk of k.lists){
                  kk['menu_id'] = k.menu_id;
                  kk['num'] = 0;
                  new_complete_datas.push(kk);
              }
          };
          self.complete_menu = new_complete_menu;
          self.complete_datas = new_complete_datas;
          self.totalPrice = 0;
          self.totalNum = 0;
          // 数量为0，弹出层消失
          self.show = false;
        },
        // 结算
        settlement(){
            self = this;
            self.modalShow = true;
            self.xshow = false;
        },
        setpopup(){
            self = this;
            if(self.xshow){
                self.xshow = false
            }else{
                self.xshow = true;
            }
        }
		}
	}
</script>

<style lang="scss" scoped>
	.u-wrap {
        /* #ifdef H5 */
        // 减去两个吸顶高度
		height: calc(100vh - 100px);
        /* #endif */
        /* #ifdef MP-WEIXIN */
        // 减去两个吸顶高度,微信小程序减去时间电池显示栏
        height: calc(100vh - 144px);
        /* #endif */
		display: flex;
		flex-direction: column;
	}

	.u-search-box {
		padding: 18rpx 30rpx;
	}

	.u-menu-wrap {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.u-search-inner {
		background-color: rgb(234, 234, 234);
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		padding: 10rpx 16rpx;
	}

	.u-search-text {
		font-size: 26rpx;
		color: $u-tips-color;
		margin-left: 10rpx;
	}

	.u-tab-view {
		width: 250rpx;
		height: 100%;
	}

	.u-tab-item {
        position: relative;
		height: 110rpx;
		background: #f6f6f6;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26rpx;
		color: #444;
		font-weight: 400;
		line-height: 1;
	}
    
    // 选中以后改变样式
	.u-tab-item-active {
		position: relative;
		color: #000;
		font-size: 29rpx;
		font-weight: 600;
		background: #fff;
	}

    // 在前面加一个竖条
	.u-tab-item-active::before {
		content: "";
		position: absolute;
		// border-left: 4px solid $u-type-primary;
         border-left: 3px solid #009ff0;
		height: 32rpx;
		left: 0;
		top: 39rpx;
	}

	.u-tab-view {
		height: 100%;
	}

	.right-box {
		// background-color: rgb(250, 250, 250);
        background-color: #fff;
	}

	.page-view {
		// padding: 16rpx;
	}

	.class-item {
		margin-bottom: 10rpx;
		background-color: #fff;
		padding: 16rpx;
		border-radius: 8rpx;
	}

	.class-item:last-child {
		min-height: 100vh;
        // min-height: 500px;
	}
    
    // 模仿支付宝上饿了吗的类别吸顶效果
	.item-title {
        position: sticky;
        /* #ifdef H5 */
        top: -1px;
        /* #endif */
        /* #ifdef MP-WEIXIN */
        top: 0;
        /* #endif */
		font-size: 35upx;
		color: $u-main-color;
		font-weight: bold;
        background-color: #fff;
        z-index: 9990;
        padding: 10px 0 10px 0;
	}

	.item-menu-name {
		font-weight: normal;
		font-size: 24rpx;
		color: $u-main-color;
	}

	.item-container {
		display: flex;
		flex-wrap: wrap;
	}

	.thumb-box {
		width: 33.333333%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		margin-top: 20rpx;
	}

	.item-menu-image {
		width: 120rpx;
		height: 120rpx;
	}
    
    .db_div {
        height: 80px;
        width: 100%;
        background-color: #fff;
        position:fixed; 
        bottom:0;
        /* 弹出层是10075 */
        z-index: 10075;
    }
    
    .db_div_show {
        height: 80px;
        width: 100%;
        background-color: #fff;
        position:fixed; 
        bottom:0; 
    }
    
    .menuDetailDiv {
        display: flex;
        flex-direction: row;
        margin-bottom: 20px;
        /* justify-content: center;
        align-items: center; */
    }
    
    .menuDetailDivImg {
        width: 100px;
    }
    
    .menu-img {
        width: 100px;
        height: 100px;
    }
    
    .menuDetailDivContent{
        margin: 0 20px 0;
        display: flex;
        flex-direction: column;
    }
    
    /* 超出宽度显示省略号
     */
    .menuDetailDivContentDetails{
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 27upx;
        color:#808080;
        width: 200rpx;
        
    }
    
    .menuDetailDivContentDetailsPrice {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
    }
    
    .menuDetailDivContentDetailsPriceDiv {
        flex-direction: row;
        align-items: baseline;
    }
    
    .presentPrice {
        color: #F08080;
        font-size:30upx;
        font-weight: bold;
    }
    
    .menuDetailDivContentDetailsoriginalPrice {
        font-size: 27upx;
        color:#808080;
    }
    
    /* 添加删除线 */
    .shanchu {
        text-decoration:line-through;
        margin-left: 10px;
    }
    
    .addNum{
        display: flex;
        position: relative;
        flex-direction: row;
        justify-content:center;
        align-items: center;
        margin: 0 2rpx;
    }
    
    .plush {
        width: 50upx;
        height: 50upx;
        background-color: #009ff0;
        border-radius: 50px;
        justify-content:center;
        align-items: center;
    }
    
    .minusSign {
        width: 50upx;
        height: 50upx;
        background-color: #ffffff;
        border-radius: 50px;
        border-style: solid;
        border-width: 1px;
        border-color: #009ff0;
        justify-content:center;
        align-items: center;
    }
    
    .menu-list-cell-num {
        position: absolute;
        /* #ifdef H5 */
        left: 130rpx;
        /* #endif */
        /* #ifdef MP-WEIXIN */
        left: 140rpx;
        /* #endif */
        top:10rpx;
        width: 40rpx;
        height: 40rpx;
        border-radius:50px;
        border-style: solid;
        border-width: 1px;
        display: flex;
        justify-content:center;
        align-items: center;
        border-color: #F08080;
        background-color: #F08080;
    }
    
    .footDivFlex {
        display: flex;
        flex-direction: row;
        justify-content: space-around;
        margin-top: 20px;
    }
    
    .footDivFlexMenu {
        display: flex;
        flex-direction: column;
    }
    
    .footDivFlexMenu text{
        font-size: 10upx;
    }
    
    .footDivFlexMenuqss {
        display: flex;
        background-color: #009ff0;
        justify-content:center;
        border-radius: 40px;
        width: 200px;
        align-items: center;
    }
    
    .footDivFlexMenuqss {
        background-color: #009ff0;
        justify-content:center;
        border-radius: 40px;
        width: 200px;
        align-items: center;
    }
    
    .wxcPopupListCell {
        display: flex;
        flex-direction: row;
        justify-content: space-around;
        align-items: center
    }
</style>

